package com.jpxx.netty.hello;

import java.net.SocketAddress;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
  
public class ServerHandler extends ChannelHandlerAdapter{  

		//数据怎么从管道读出来，怎么做处理，在这里
		//ChannelHandlerContext整个通道的上下文，类似spring的applicationContext
		@Override  
	    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {  
			System.out.println("通道读写-channelRead-");
			 
			//msg默认就是比buffer类型，可以直接强转
			//ByteBuf不是 java.nio.ByteBuffer，netty封装的操作起来更简单
			ByteBuf buf = (ByteBuf)msg;
			
			byte[] req = new byte[buf.readableBytes()];//可读的字节数
			buf.readBytes(req);//把缓冲里的数据 去读到上面新创建的字节数组里面
			
			//7E  02 10: 00  2F  00 17  05  10  53 04 00 00 00 00 00 00 00 00 00 7E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  18  05 09  10  39  08 01 04 00 00 00 00 03 02 00 00  30 01 00  25 04 00 00 00 00  59   7E
			//[126, 2, 0,  0, 47, 0, 23,  5, 16, 83, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24,  5, 9, 19, 51, 52, 1, 4, 0, 0, 0, 0, 3, 2, 0, 0, 48, 1, 0, 37, 4, 0, 0, 0, 0, 108, 126]
			
			//输出从客户端拿到的数据，转成utf-8 打印
			//[126, 1, 0, 0, 45, 0, 23, 5, 16, 83, 4, 0, 1, 0, 44, 1, 47, 55, 48, 49, 48, 53, 66, 78, 84, 52, 48, 48, 48, 72, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 55, 53, 48, 53, 51, 57, 50, 2, -78, -30, 72, 66, 49, 48, 55, 56, 112, 126]
			String body = new String(req,"utf-8");
			System.out.println("Server服务端:"+body);
			
			//服务器端给客户端的回复 响应
			String response = "你好客户端。。。。我是server";
		
			//只要有写操作   自动帮我释放引用计数器对象  不需要ReferenceCountUtil.release(msg);
			ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
			
			//加上下面这段代码，服务端接受一次客户端的连接就会自动跟客户端断开
			//.addListeners(ChannelFutureListener.CLOSE)
	    }  
	      
		//抛异常的时候，怎么处理 在这里
	    @Override  
	    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {  
	    	System.out.println("异常处理");  
	        cause.printStackTrace();  
	        ctx.close();  
	    }

		@Override
		public void channelActive(ChannelHandlerContext ctx) throws Exception {
			System.out.println("通道激活（活跃时），channelActive");
			super.channelActive(ctx);
		}
		

		@Override
		public void channelReadComplete(ChannelHandlerContext ctx)
				throws Exception {
			System.out.println("通道读取结束channelReadComplete");
			super.channelReadComplete(ctx);
		}

    
} 